
#import "PUPublishVC.h"
#import "UITextView+YLTextView.h"
#import "TZImagePickerController.h"
#import "UIView+TZLayout.h"
#import "TZTestCell.h"
#import <Photos/Photos.h>
#import "LxGridViewFlowLayout.h"
#import "TZImageManager.h"
#import "TZPhotoPreviewController.h"
#import "TZGifPhotoPreviewController.h"
#import "TZAssetCell.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "FLAnimatedImage.h"
#import "TZImageUploadOperation.h"
#import "TZVideoEditedPreviewController.h"
#import "BRPickerView.h"
#import "UIButton+AxcButtonContentLayout.h"
#import "PUDTHTSelView.h"
#import "PUTipView.h"
#import "IQKeyboardManager.h"
#import "IQKeyboardReturnKeyHandler.h"
#import "QCloudCOSXML.h"
@interface PUPublishVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,TZImagePickerControllerDelegate,UINavigationControllerDelegate,FLDTHTSelViewDelegate,CPTipViewDelegate>
{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto;
    BOOL _isAllowEditVideo;
    
    CGFloat _itemWH;
    CGFloat _margin;
    
    NSString * uploadFilePath;
    int originConstraintValue;
}
@property(nonatomic,retain)NSString *reportStr;
@property(nonatomic,retain)UILabel *JBLab;
@property(nonatomic,retain)UITextView *textView;
@property(nonatomic,retain)UILabel *JBNRlab;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) LxGridViewFlowLayout *layout;
@property (nonatomic, strong) CLLocation *location;
@property (nonatomic, strong) NSOperationQueue *operationQueue;
@property(nonatomic,retain)UIButton *huatiBtn;
@property (nonatomic,retain)UIView *huatiView;
@property (nonatomic,retain)UIView *noHuatiView;
@property (nonatomic,retain)UIImageView *img2;
@property (nonatomic,retain)UIButton *xzhtBtn2;
@property (nonatomic,retain)UIButton *tjhtBtn2;
@property (nonatomic,retain)UILabel *numLab;
@property(nonatomic,retain)NSMutableArray *imageData;
@property(nonatomic,retain)NSMutableArray *imagefileNameData;
@property(nonatomic,retain)NSData *videoData;
@property(nonatomic,retain)NSData *coverData;

@property(nonatomic,retain)NSString *videoUrl;
@property(nonatomic,retain)NSString *coverUrl;
@property(nonatomic)CGFloat width;
@property(nonatomic)CGFloat height;
@property (nonatomic,retain)UITextField *textField1;
@property (nonatomic,retain)UITextField *textField2;
@property(nonatomic)int count;
@property(nonatomic,retain)UILabel *countlab;
@end

@implementation PUPublishVC


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor=[UIColor whiteColor];
    self.reportStr=@"";
    if (self.huaTiStr==nil) {
        self.huaTiStr=@"";
    }
    self.count=1;
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    self.imageData=[NSMutableArray array];
    self.imagefileNameData=[NSMutableArray array];


    //右菜单栏目
    UIView *butV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 36*KWidthScale, 25*KWidthScale)];
    UIButton *rightbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightbtn.frame = CGRectMake(0, 0, 48*KWidthScale,25*KWidthScale);
    [rightbtn setTitle:@"发布" forState:UIControlStateNormal];
    rightbtn.titleLabel.font = [UIFont boldSystemFontOfSize:13];
    [rightbtn setBackgroundColor:[UIColor colorWithHex:0xFF729A]];
    [rightbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightbtn addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    rightbtn.layer.masksToBounds=YES;
    rightbtn.layer.cornerRadius = 25*KWidthScale/2;
    [butV addSubview:rightbtn];
    UIBarButtonItem *rightitem = [[UIBarButtonItem alloc] initWithCustomView:butV];
    self.navigationItem.rightBarButtonItem=rightitem;
    
    
    UIView *xian=[[UIView alloc]init];
    xian.backgroundColor=[UIColor colorWithHex:0xF3F3F3];
    [self.view addSubview:xian];
    
    [xian mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(0);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
//        make.bottom.equalTo(self.view.mas_bottom).offset(0);
        make.height.equalTo(@(12));
    }];
    
    
    UIView *view1=[[UIView alloc]init];
    view1.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:view1];
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(12*KWidthScale);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(-0);
//        make.bottom.equalTo(self.view.mas_bottom).offset(0);
        make.height.equalTo(@(_window_width/3-10*KWidthScale+8*KWidthScale+144*KWidthScale));
    }];
    
    
    
    // 如不需要长按排序效果，将LxGridViewFlowLayout类改成UICollectionViewFlowLayout即可
    _layout = [[LxGridViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
//    _collectionView.backgroundColor = [UIColor blueColor];
    _collectionView.scrollEnabled=NO;
    _collectionView.contentInset = UIEdgeInsetsMake(4, 4, 4, 4);
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [view1 addSubview:_collectionView];
    [_collectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
    
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view1.mas_top).offset(8*KWidthScale);
        make.left.equalTo(view1.mas_left).offset(8*KWidthScale);
        make.right.equalTo(view1.mas_right).offset(-8*KWidthScale);
//        make.bottom.equalTo(self.view.mas_bottom).offset(0);
        make.height.equalTo(@(_window_width/3-10*KWidthScale));
    }];
    
    self.textView=[[UITextView alloc]init];
    self.textView.delegate=self;
//    self.textView.clipsToBounds = YES;
//    self.textView.layer.cornerRadius =10;
//    self.textView.frame=CGRectMake( _window_width*0.042,10+_window_width*0.042, _window_width*0.914,_window_width*0.914*0.524);
    self.textView.placeholder = @"这一刻的想法……";//占位符
//    self.textView.limitLength = @100;//字数限制
    self.textView.font = [UIFont systemFontOfSize:14];
//    self.textView.backgroundColor=[UIColor redColor];
    [self.view addSubview:self.textView];
    
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_collectionView.mas_bottom).offset(4*KWidthScale);
        make.left.equalTo(view1.mas_left).offset(8*KWidthScale);
        make.right.equalTo(view1.mas_right).offset(-8*KWidthScale);
        make.bottom.equalTo(view1.mas_bottom).offset(0);
//        make.height.equalTo(@(_window_width/3-10*KWidthScale));
    }];
    
//    UIView *view2=[[UIView alloc]init];
//    view2.backgroundColor=[UIColor whiteColor];
//    [self.view addSubview:view2];
//    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view1.mas_bottom).offset(12*KWidthScale);
//        make.left.equalTo(self.view.mas_left).offset(0);
//        make.right.equalTo(self.view.mas_right).offset(0);
////        make.bottom.equalTo(self.view.mas_bottom).offset(0);
//        make.height.equalTo(@(48*KWidthScale));
//    }];
//
//    self.textField1 = [[UITextField alloc]init];
//    self.textField1.font = [UIFont systemFontOfSize:14.0f];
//    self.textField1.textAlignment = NSTextAlignmentLeft;
//    self.textField1.textColor=[UIColor blackColor];
//    self.textField1.placeholder=@"请输入花名";
//    [view2 addSubview:self.textField1];
//
//    [self.textField1 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view2.mas_top).offset(0);
//        make.left.equalTo(view2.mas_left).offset(12);
//        make.right.equalTo(view2.mas_right).offset(0);
////        make.bottom.equalTo(self.view.mas_bottom).offset(0);
//        make.height.equalTo(@(48*KWidthScale));
//    }];
//
//    UIView *view3=[[UIView alloc]init];
//    view3.backgroundColor=[UIColor whiteColor];
//    view3.userInteractionEnabled=YES;
//    UITapGestureRecognizer *view3Tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(view3TapGesture)];
//
//    [view3 addGestureRecognizer:view3Tap];
//    [self.view addSubview:view3];
//    [view3 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view2.mas_bottom).offset(12*KWidthScale);
//        make.left.equalTo(self.view.mas_left).offset(0);
//        make.right.equalTo(self.view.mas_right).offset(0);
////        make.bottom.equalTo(self.view.mas_bottom).offset(0);
//        make.height.equalTo(@(48*KWidthScale));
//    }];
//
//    UILabel *lab3 = [[UILabel alloc] init];
//    lab3.font=[UIFont systemFontOfSize:15];
//    lab3.textColor = [UIColor blackColor];
//    lab3.text=@"价格";
//    [view3 addSubview:lab3];
//
//    [lab3 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view3.mas_top).offset(0);
//        make.left.equalTo(view3.mas_left).offset(12*KWidthScale);
//        make.right.equalTo(view3.mas_right).offset(0);
//        make.bottom.equalTo(view3.mas_bottom).offset(0);
////        make.height.equalTo(@(48*KWidthScale));
//    }];
//
//    UIImageView *imgJT=[[UIImageView alloc]init];
//    imgJT.image=[UIImage imageNamed:@"huaJT"];
//    [view3 addSubview:imgJT];
//
//    [imgJT mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view3.mas_top).offset(15*KWidthScale);
////        make.left.equalTo(view3.mas_left).offset(12*KWidthScale);
//        make.right.equalTo(view3.mas_right).offset(-12*KWidthScale);
////        make.bottom.equalTo(view3.mas_bottom).offset(0);
//        make.width.equalTo(@(16*KWidthScale));
//        make.height.equalTo(@(16*KWidthScale));
//    }];
//
//    UIImageView *imgJB=[[UIImageView alloc]init];
//    imgJB.image=[UIImage imageNamed:@"hua金币"];
//    [view3 addSubview:imgJB];
//
//    [imgJB mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view3.mas_top).offset(15*KWidthScale);
////        make.left.equalTo(view3.mas_left).offset(12*KWidthScale);
//        make.right.equalTo(imgJT.mas_left).offset(-8*KWidthScale);
////        make.bottom.equalTo(view3.mas_bottom).offset(0);
//        make.width.equalTo(@(16*KWidthScale));
//        make.height.equalTo(@(16*KWidthScale));
//    }];
//
//    self.textField2 = [[UITextField alloc]init];
//    self.textField2.font = [UIFont boldSystemFontOfSize:16];
//    self.textField2.textAlignment = NSTextAlignmentRight;
//    self.textField2.textColor=[UIColor colorWithHex:0xFF729A];
//    self.textField2.keyboardType=UIKeyboardTypeNumberPad;
//    self.textField2.placeholder=@"0";
//    [view3 addSubview:self.textField2];
////    self.textField2.backgroundColor=[UIColor blueColor];
//    [self.textField2 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view3.mas_top).offset(0);
////        make.left.equalTo(lab3.mas_right).offset(12*KWidthScale);
//        make.right.equalTo(imgJB.mas_left).offset(-8*KWidthScale);
//        make.bottom.equalTo(view3.mas_bottom).offset(-8*KWidthScale);
//        make.width.equalTo(@(150*KWidthScale));
////        make.height.equalTo(@(16*KWidthScale));
//    }];
//
//
//    NSString *str=@"0";
//    NSString *app_icp=str;
//    NSString *topStr=app_icp;
//    NSString *s=[NSString stringWithFormat:@"%@",topStr];
//    self.textField2.text=s;
//    NSMutableAttributedString *hogan1 = [[NSMutableAttributedString alloc] initWithString:s];
//    [hogan1 addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:NSMakeRange(0, s.length)];
//    [hogan1 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0xFF729A] range:NSMakeRange(0, s.length)];
//    [hogan1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(0, 1)];
//    [hogan1 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0xFF729A] range:NSMakeRange(0,1)];
//    self.textField2.attributedText = hogan1;
//
//
//
//    UIView *view4=[[UIView alloc]init];
//    view4.backgroundColor=[UIColor whiteColor];
//    [self.view addSubview:view4];
//    [view4 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view3.mas_bottom).offset(12*KWidthScale);
//        make.left.equalTo(self.view.mas_left).offset(0);
//        make.right.equalTo(self.view.mas_right).offset(0);
////        make.bottom.equalTo(self.view.mas_bottom).offset(0);
//        make.height.equalTo(@(48*KWidthScale));
//    }];
//
//    UILabel *lab4 = [[UILabel alloc] init];
//    lab4.font=[UIFont systemFontOfSize:15];
//    lab4.textColor = [UIColor blackColor];
//    lab4.text=@"数量";
//    [view4 addSubview:lab4];
//
//    [lab4 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view4.mas_top).offset(0);
//        make.left.equalTo(view4.mas_left).offset(12*KWidthScale);
//        make.right.equalTo(view4.mas_right).offset(0);
//        make.bottom.equalTo(view4.mas_bottom).offset(0);
////        make.height.equalTo(@(48*KWidthScale));
//    }];
//
//    UIButton *btnjia=[[UIButton alloc]init];
//    [btnjia addTarget:self action:@selector(btnjiaClick) forControlEvents:UIControlEventTouchUpInside];
//    [btnjia setImage:[UIImage imageNamed:@"huajia"] forState:UIControlStateNormal];
//    [view4 addSubview:btnjia];
//    [btnjia mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view4.mas_top).offset(16*KWidthScale);
////        make.left.equalTo(view3.mas_left).offset(12*KWidthScale);
//        make.right.equalTo(view4.mas_right).offset(-12*KWidthScale);
////        make.bottom.equalTo(view3.mas_bottom).offset(0);
//        make.width.equalTo(@(16*KWidthScale));
//        make.height.equalTo(@(16*KWidthScale));
//    }];
//
//
//    UIButton *btnjian=[[UIButton alloc]init];
//    [btnjian addTarget:self action:@selector(btnjianClick) forControlEvents:UIControlEventTouchUpInside];
//    [btnjian setImage:[UIImage imageNamed:@"huajian"] forState:UIControlStateNormal];
//    [view4 addSubview:btnjian];
//    [btnjian mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view4.mas_top).offset(16*KWidthScale);
////        make.left.equalTo(view3.mas_left).offset(12*KWidthScale);
//        make.right.equalTo(view4.mas_right).offset(-100*KWidthScale);
////        make.bottom.equalTo(view3.mas_bottom).offset(0);
//        make.width.equalTo(@(16*KWidthScale));
//        make.height.equalTo(@(16*KWidthScale));
//    }];
//
//    self.countlab = [[UILabel alloc] init];
//    self.countlab.font=[UIFont systemFontOfSize:15];
//    self.countlab.textColor = [UIColor blackColor];
//    self.countlab.text=[NSString stringWithFormat:@"%d",self.count];
//    self.countlab.textAlignment=NSTextAlignmentCenter;
//    self.countlab.backgroundColor=[UIColor colorWithHex:0xF3F3F3];
//    self.countlab.layer.masksToBounds=YES;
//    self.countlab.layer.cornerRadius = 4;
//    [view4 addSubview:self.countlab];
//    [self.countlab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view4.mas_top).offset(12*KWidthScale);
////        make.left.equalTo(view3.mas_left).offset(12*KWidthScale);
//        make.right.equalTo(view4.mas_right).offset(-40*KWidthScale);
////        make.bottom.equalTo(view3.mas_bottom).offset(0);
//        make.width.equalTo(@(48*KWidthScale));
//        make.height.equalTo(@(24*KWidthScale));
//    }];
    
    //IQKeyboardManager最后还设置回来,不要影响其他页面的效果
    IQKeyboardManager *keyboardManager =  [IQKeyboardManager sharedManager];
    keyboardManager.enable = YES;
    keyboardManager.enableAutoToolbar = YES;
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)view3TapGesture{
    [self.textField2 becomeFirstResponder];
}
-(void)btnjiaClick{
    self.count=self.count+1;
    self.countlab.text=[NSString stringWithFormat:@"%d",self.count];
}
-(void)btnjianClick{
    if (self.count==1) {
        return;
    }
    self.count=self.count-1;
    self.countlab.text=[NSString stringWithFormat:@"%d",self.count];
}


-(void)buttonAction{
    
    if(_selectedPhotos.count==0){
        [self showSVProgressHUDStr:@"请添加图片后发布"];
        return;
    }
    if ([[self.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0) {
        [self showSVProgressHUDStr:@"请输入这一刻的想法……"];
        return;
    }
    
    NSMutableArray *images=[NSMutableArray array];
    for (int i=0; i<_selectedPhotos.count; i++) {
        UIImage *image=self->_selectedPhotos[i];
        [images addObject:image];
    }
    
    
    NSMutableArray *data=[NSMutableArray array];
    //创建一个归档文件夹
    NSArray *library = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *strLib = [[library objectAtIndex:0] stringByAppendingPathComponent:@"archive"];
    BOOL directory = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:strLib isDirectory:&directory])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:strLib withIntermediateDirectories:NO attributes:nil error:nil];
    }
    //归档
    NSString *entityArchive = [strLib stringByAppendingPathComponent:[NSString stringWithFormat:@"dongtaiDataArchive%@",[Config getID]]];
//    [NSKeyedArchiver archiveRootObject:data toFile:entityArchive];
    //数据源从归档中读出
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
    NSLog(@"%@",array);
    if(array.count==0){
        array=[NSMutableArray array];
    }
    
    NSDictionary * d1 = @{
                          @"username":[Config getnickname],
                          @"userimage":[Config getOriginal_avatar],
                          @"userid":[Config getID],
//                          @"userAddress":self.userAddress,
//                          @"flowers_name":self.textField1.text,
                          @"flowers_image":images,
//                          @"flowers_JG":self.textField2.text,
//                          @"flowers_buyCount":[NSString stringWithFormat:@"%d",self.count],
                          @"flowers_buyTime":[self getCurrentTimes],
                          @"flowers_describe":self.textView.text,
                          
                         };
    [array insertObject:d1 atIndex:0];
    [NSKeyedArchiver archiveRootObject:array toFile:entityArchive];
    NSMutableArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
    NSLog(@"%@",array2);
    [self showSVProgressHUDStr:@"发布成功"];
    [self.navigationController popViewControllerAnimated:NO];
    if (self.isGHEnter!=1) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"pushGHJLNotification" object:self userInfo:nil];//跳转到观花记录
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"relodGHJLNotification" object:self userInfo:nil];//刷新观花记录玉面
    }
    
    
}
//获取当前的时间
-(NSString*)getCurrentTimes{
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
     [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
     //现在时间,你可以输出来看下是什么格式
     NSDate *datenow = [NSDate date];
     //----------将nsdate按formatter格式转成nsstring
     NSString *currentTimeString = [formatter stringFromDate:datenow];
     NSLog(@"currentTimeString =  %@",currentTimeString);
     return currentTimeString;
}
-(void)closeBtnAction{
    self.huaTiStr=@"";
    self.noHuatiView.hidden=NO;
    self.huatiView.hidden=YES;
    
}
//添加话题
-(void)tjhtGesture{

    PUDTHTSelView *v = [[PUDTHTSelView alloc]initCPPDMoreViewViewWith:@[]];
    v.delegate = self;
    [v show];
}

-(void)selectIndex:(int)index{
    NSLog(@"%d",index);
    
    self.huaTiStr=@"心动搭讪";
    [self.huatiBtn setTitle:self.huaTiStr forState:UIControlStateNormal];//
    self.noHuatiView.hidden=YES;
    self.huatiView.hidden=NO;
    
    
    CGSize size = [self.huaTiStr sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16]}];
    CGFloat width = ceil(size.width);
    
    //#
    self.huatiBtn.frame = CGRectMake(self.img2.frame.origin.x+self.img2.frame.size.width+4, 0, width,self.huatiView.frame.size.height);
    //关闭
    self.tjhtBtn2.frame = CGRectMake(self.huatiBtn.frame.origin.x+self.huatiBtn.frame.size.width+4, self.huatiView.frame.size.height*0.181, self.huatiView.frame.size.height*0.636,self.huatiView.frame.size.height*0.636);
    CGFloat w=self.tjhtBtn2.frame.origin.x+self.tjhtBtn2.frame.size.width+self.huatiView.frame.size.height*0.272;
    self.huatiView.frame = CGRectMake(_window_width*0.042, self.numLab.frame.origin.y+self.numLab.frame.size.height+16, w,self.view.frame.size.width*0.117);
    
}


-(void)backBtnAction{
    [self.textView resignFirstResponder];
//    CPTipView *view =[[CPTipView alloc]initCPTipViewWithContent:@"确认放弃当前动态吗？" title:@"温馨提示" confirmStr:@"确定" cancelStr:@"取消" buttonCount:2];
//    view.delegate=self;
//    [view show];
    
    UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"" message:@"要放弃发布动态吗" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
      
        
    }];
    
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"放弃" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        
    }];
    
    [alerController addAction:cancelAction];
    [alerController addAction:confirmAction];
    
    [self presentViewController:alerController animated:YES completion:^{
        
    }];
}

-(void)btnClickedIndex:(int)index{
    if (index==1) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    NSInteger contentSizeH = 14 * 35 + 20;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        self.scrollView.contentSize = CGSizeMake(0, contentSizeH + 5);
    });
//    if (self.scrollView.tz_height + 80 > self.view.tz_height) {
//        self.scrollView.tz_height = self.view.tz_height - 80;
//    }
    
    _margin = 4;
    _itemWH = (self.view.tz_width*0.914 - 2 * _margin - 4) / 3 - _margin;//修改每行的个数，3表示每行显示3个
    _layout.itemSize = CGSizeMake(_itemWH, _itemWH);
    _layout.minimumInteritemSpacing = _margin;
    _layout.minimumLineSpacing = _margin;
    [self.collectionView setCollectionViewLayout:_layout];
//    CGFloat collectionViewY = CGRectGetMaxY(self.scrollView.frame);
//    CGFloat collectionViewY = 50;
//    self.collectionView.frame = CGRectMake(0, collectionViewY, self.view.tz_width, self.view.tz_height - collectionViewY);
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)submitBtnClick{
//    if([self.reportStr isEqualToString:@""]){
//        NSLog(@"%@",self.textView.text);
//        [self showSVProgressHUDStr:@"请选择举报内容"];
//        return;
//    }
    
    if ([[self.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0) {
        [self showSVProgressHUDStr:@"请填写动态内容"];
        return;
    }
    
    if(_selectedPhotos.count==0){
        [self showSVProgressHUDStr:@"请添加图片/视频后发布"];
        return;
    }
//    [self loadBeforeCheck];
    
    [self loadUpload_token];

//    [self loadAddDongTai];
}
-(void)loadBeforeCheck{
//    NSString *url = [NSString stringWithFormat:@"%@/before_check",blogpurl];
//    [[AFNetManager shareManager] getDataWithURLString:url parameters:nil success:^(NSURLResponse *operation, id successObject) {
//        NSLog(@"%@",successObject);
//        if ([successObject[@"code"] integerValue] == 0) {
//            
//            [self loadputImageTokenwidth:0.0 height:0.0];
//
//        }else{
//            [self showSVProgressHUDStr:successObject[@"message"]];
//        }
//      
//    } failure:^(NSError *error) {
//        NSLog(@"%@",error);
//    }];
}
-(void)loadAddDongTai{
//    NSString *url = [NSString stringWithFormat:@"%@/add",blogpurl];
//    NSDictionary *param = @{
//                            @"type":[NSString stringWithFormat:@"%d",self.type],
//                            @"content":self.textView.text,
//                            @"media":@"11",
//                            };
//    [[AFNetManager shareManager] postDataWithURLString:url parameters:param success:^(NSURLResponse *operation, id successObject) {
//        NSLog(@"%@",successObject);
//       
//        if ([successObject[@"code"] integerValue] == 0) {
//            [self showSVProgressHUDStr:successObject[@"message"]];
//            [self.navigationController popViewControllerAnimated:YES];
//           
//        } else {
//            [self showSVProgressHUDStr:successObject[@"message"]];
//        }
//        
//    } failure:^(NSError *error) {
//        NSLog(@"%@",error);
//    }];
}

-(void)showSVProgressHUDStr:(NSString *)str{
    if ([str isKindOfClass:[NSNull class]]||str==nil||[str isEqualToString:@""]) {
        return;
    }
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD showImage:[UIImage imageNamed:@""] status:str];
}

#pragma mark UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (_selectedPhotos.count >= 3) {
        return _selectedPhotos.count;
    }
    BOOL allowPickingMuitlpleVideoSwitch=YES;
    if (allowPickingMuitlpleVideoSwitch) {
        if (_isAllowEditVideo) {
            return 1;
        } else {
            for (PHAsset *asset in _selectedAssets) {
                if (asset.mediaType == PHAssetMediaTypeVideo) {
                    return _selectedPhotos.count;
                }
            }
        }
    }
    return _selectedPhotos.count + 1;
    
//    if (_selectedPhotos.count >= 9) {
//        return _selectedPhotos.count;
//    }else{
//        return _selectedPhotos.count + 1;
//    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    if (indexPath.item == _selectedPhotos.count) {
        cell.pictureView.image = [UIImage imageNamed:@"AlbumAddBtn"];
        cell.deleteBtn.hidden = YES;
        cell.gifLable.hidden = YES;
    } else {
        cell.pictureView.image = _selectedPhotos[indexPath.item];
        if (!_isAllowEditVideo) {
            cell.asset = _selectedAssets[indexPath.item];
            
        }
        if (self.type==2) {
            cell.videoImageView.hidden = NO;
        }
        cell.deleteBtn.hidden = NO;
    }
//    if (!self.allowPickingGifSwitch.isOn) {
        cell.gifLable.hidden = YES;
//    }
    cell.deleteBtn.tag = indexPath.item;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == _selectedPhotos.count) {
//        BOOL showSheet = self.showSheetSwitch.isOn;
//        if (showSheet) {
//            NSString *takePhotoTitle = @"拍照";
//            if (self.showTakeVideoBtnSwitch.isOn && self.showTakePhotoBtnSwitch.isOn) {
//                takePhotoTitle = @"相机";
//            } else if (self.showTakeVideoBtnSwitch.isOn) {
//                takePhotoTitle = @"拍摄";
//            }
//            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//            UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:takePhotoTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                [self takePhoto];
//            }];
//            [alertVc addAction:takePhotoAction];
//            UIAlertAction *imagePickerAction = [UIAlertAction actionWithTitle:@"去相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                [self pushTZImagePickerController];
//            }];
//            [alertVc addAction:imagePickerAction];
//            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//            [alertVc addAction:cancelAction];
//            UIPopoverPresentationController *popover = alertVc.popoverPresentationController;
//            UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
//            if (popover) {
//                popover.sourceView = cell;
//                popover.sourceRect = cell.bounds;
//                popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
//            }
//            [self presentViewController:alertVc animated:YES completion:nil];
//        } else {
            [self pushTZImagePickerController];
//        }
    } else if (_isAllowEditVideo && [_selectedAssets[indexPath.item] isKindOfClass:[NSURL class]]) { // preview edited video / 预览编辑后的视频
        TZVideoEditedPreviewController *vc = [[TZVideoEditedPreviewController alloc] init];
        vc.videoURL = _selectedAssets[indexPath.item];
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:vc animated:YES completion:nil];
    } else { // preview photos or video / 预览照片或者视频
        PHAsset *asset = _selectedAssets[indexPath.item];
        BOOL isVideo = NO;
        isVideo = asset.mediaType == PHAssetMediaTypeVideo;
        if ([[asset valueForKey:@"filename"] containsString:@"GIF"] ) {
            TZGifPhotoPreviewController *vc = [[TZGifPhotoPreviewController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypePhotoGif timeLength:@""];
            vc.model = model;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        } else if (isVideo ) { // perview video / 预览视频
            TZVideoPlayerController *vc = [[TZVideoPlayerController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo timeLength:@""];
            vc.model = model;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        } else { // preview photos / 预览照片
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.item];
            imagePickerVc.maxImagesCount = 3;
            imagePickerVc.allowPickingGif = NO;
            imagePickerVc.autoSelectCurrentWhenDone = NO;
            imagePickerVc.allowPickingOriginalPhoto = NO;
            imagePickerVc.allowPickingMultipleVideo = NO;
            imagePickerVc.showSelectedIndex = YES;
            imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
            imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                self->_selectedPhotos = [NSMutableArray arrayWithArray:photos];
                self->_selectedAssets = [NSMutableArray arrayWithArray:assets];
                self->_isSelectOriginalPhoto = isSelectOriginalPhoto;
                [self->_collectionView reloadData];
                self->_collectionView.contentSize = CGSizeMake(0, ((self->_selectedPhotos.count + 2) / 3 ) * (self->_margin + self->_itemWH));
            }];
            [self presentViewController:imagePickerVc animated:YES completion:nil];
        }
    }
}

#pragma mark - LxGridViewDataSource

/// 以下三个方法为长按排序相关代码
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.item < _selectedPhotos.count;
}

- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath canMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    return (sourceIndexPath.item < _selectedPhotos.count && destinationIndexPath.item < _selectedPhotos.count);
}

- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    UIImage *image = _selectedPhotos[sourceIndexPath.item];
    [_selectedPhotos removeObjectAtIndex:sourceIndexPath.item];
    [_selectedPhotos insertObject:image atIndex:destinationIndexPath.item];
    
    id asset = _selectedAssets[sourceIndexPath.item];
    [_selectedAssets removeObjectAtIndex:sourceIndexPath.item];
    [_selectedAssets insertObject:asset atIndex:destinationIndexPath.item];
    
    [_collectionView reloadData];
}

#pragma mark - TZImagePickerController

- (void)pushTZImagePickerController {
//    if (self.maxCountTF.text.integerValue <= 0) {
//        return;
//    }
    // 设置languageBundle以使用其它语言，必须在TZImagePickerController初始化前设置 / Set languageBundle to use other language
//     [TZImagePickerConfig sharedInstance].languageBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"zh-Hans" ofType:@"lproj"]];

    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    
#pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    
//    if (self.maxCountTF.text.integerValue > 1) {
        // 1.设置目前已经选中的图片数组
        imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
//    }
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
    imagePickerVc.videoMaximumDuration = 10; // 视频最大拍摄时间
    imagePickerVc.allowEditVideo = YES; // 允许编辑视频
    // imagePickerVc.saveEditedVideoToCollection = YES; // 编辑后的视频是否自动保存到相册
    // imagePickerVc.maxCropVideoDuration = 30; // 裁剪视频的最大时长
    // imagePickerVc.presetName = AVAssetExportPresetMediumQuality // 编辑后的视频的导出质量
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    // imagePickerVc.autoSelectCurrentWhenDone = NO;
    
    // imagePickerVc.photoWidth = 1600;
    // imagePickerVc.photoPreviewMaxWidth = 1600;
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    // imagePickerVc.barItemTextColor = [UIColor blackColor];
    // imagePickerVc.navigationBar.translucent = NO;
    // [imagePickerVc.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}];
    // imagePickerVc.navigationBar.tintColor = [UIColor blackColor];
    // if (@available(iOS 13.0, *)) {
    //     UINavigationBarAppearance *barAppearance = [[UINavigationBarAppearance alloc] init];
    //     barAppearance.backgroundColor = imagePickerVc.navigationBar.barTintColor;
    //     barAppearance.titleTextAttributes = imagePickerVc.navigationBar.titleTextAttributes;
    //     imagePickerVc.navigationBar.standardAppearance = barAppearance;
    //     imagePickerVc.navigationBar.scrollEdgeAppearance = barAppearance;
    // }
    
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    /*
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
     */
    /*
    [imagePickerVc setAssetCellDidSetModelBlock:^(TZAssetCell *cell, UIImageView *imageView, UIImageView *selectImageView, UILabel *indexLabel, UIView *bottomView, UILabel *timeLength, UIImageView *videoImgView) {
        cell.contentView.clipsToBounds = YES;
        cell.contentView.layer.cornerRadius = cell.contentView.tz_width * 0.5;
    }];
     */
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    
    
    
    
    if (self.type==1) {
        imagePickerVc.allowPickingVideo = NO;
        imagePickerVc.allowPickingImage = YES;
    }else{
        imagePickerVc.allowPickingVideo = YES;
        imagePickerVc.allowPickingImage = NO;
    }
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingMultipleVideo = NO; // 是否可以多选视频
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    
    // imagePickerVc.minImagesCount = 3;
    // imagePickerVc.alwaysEnableDoneBtn = YES;
    
    // imagePickerVc.minPhotoWidthSelectable = 3000;
    // imagePickerVc.minPhotoHeightSelectable = 2000;
    
    /// 5. Single selection mode, valid when maxImagesCount = 1
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    // 设置竖屏下的裁剪尺寸
    NSInteger left = 30;
    NSInteger widthHeight = self.view.tz_width - 2 * left;
    NSInteger top = (self.view.tz_height - widthHeight) / 2;
    if ([TZCommonTools tz_isLandscape]) {
        top = 30;
        widthHeight = self.view.tz_height - 2 * left;
        left = (self.view.tz_width - widthHeight) / 2;
    }
    imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    imagePickerVc.scaleAspectFillCrop = YES;
    // 设置横屏下的裁剪尺寸
    // imagePickerVc.cropRectLandscape = CGRectMake((self.view.tz_height - widthHeight) / 2, left, widthHeight, widthHeight);
    /*
     [imagePickerVc setCropViewSettingBlock:^(UIView *cropView) {
     cropView.layer.borderColor = [UIColor redColor].CGColor;
     cropView.layer.borderWidth = 2.0;
     }];*/
    
    // imagePickerVc.allowPreview = NO;
    // 自定义导航栏上的返回按钮
    /*
    [imagePickerVc setNavLeftBarButtonSettingBlock:^(UIButton *leftButton){
        [leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
        [leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 20)];
    }];
    imagePickerVc.delegate = self;
    */
    
    // Deprecated, Use statusBarStyle
    // imagePickerVc.isStatusBarDefault = NO;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = YES;
    
    // 设置拍照时是否需要定位，仅对选择器内部拍照有效，外部拍照的，请拷贝demo时手动把pushImagePickerController里定位方法的调用删掉
    // imagePickerVc.allowCameraLocation = NO;
    
    // 自定义gif播放方案
    [[TZImagePickerConfig sharedInstance] setGifImagePlayBlock:^(TZPhotoPreviewView *view, UIImageView *imageView, NSData *gifData, NSDictionary *info) {
        FLAnimatedImage *animatedImage = [FLAnimatedImage animatedImageWithGIFData:gifData];
        FLAnimatedImageView *animatedImageView;
        for (UIView *subview in imageView.subviews) {
            if ([subview isKindOfClass:[FLAnimatedImageView class]]) {
                animatedImageView = (FLAnimatedImageView *)subview;
                animatedImageView.frame = imageView.bounds;
                animatedImageView.animatedImage = nil;
            }
        }
        if (!animatedImageView) {
            animatedImageView = [[FLAnimatedImageView alloc] initWithFrame:imageView.bounds];
            animatedImageView.runLoopMode = NSDefaultRunLoopMode;
            [imageView addSubview:animatedImageView];
        }
        animatedImageView.animatedImage = animatedImage;
    }];
    
    // 设置首选语言 / Set preferred language
    // imagePickerVc.preferredLanguage = @"zh-Hans";
    
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {

    }];
    
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


// 调用相机
- (void)pushImagePickerController {
#ifdef TZ_HAVE_LOCATION_CODE
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locations) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = [locations firstObject];
    } failureBlock:^(NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = nil;
    }];
#endif

//    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
//    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
//        self.imagePickerVc.sourceType = sourceType;
//        NSMutableArray *mediaTypes = [NSMutableArray array];
//        if (self.showTakeVideoBtnSwitch.isOn) {
//            [mediaTypes addObject:(NSString *)kUTTypeMovie];
//        }
//        if (self.showTakePhotoBtnSwitch.isOn) {
//            [mediaTypes addObject:(NSString *)kUTTypeImage];
//        }
//        if (mediaTypes.count) {
//            _imagePickerVc.mediaTypes = mediaTypes;
//        }
//        [self presentViewController:_imagePickerVc animated:YES completion:nil];
//    } else {
//        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
//    }
}

// The picker should dismiss itself; when it dismissed these handle will be called.
// You can also set autoDismiss to NO, then the picker don't dismiss itself.
// If isOriginalPhoto is YES, user picked the original photo.
// You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:].
// The UIImage Object in photos default width is 828px, you can set it by photoWidth property.
// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 你也可以设置autoDismiss属性为NO，选择器就不会自己dismis了
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    _isAllowEditVideo = NO;
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [_collectionView reloadData];
    // _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));

    // 1.打印图片名字
    [self printAssetsName:assets];
    // 2.图片位置信息
    for (PHAsset *phAsset in assets) {
        NSLog(@"location:%@",phAsset.location);
    }

    // 3. 获取原图的示例，用队列限制最大并发为1，避免内存暴增
    self.operationQueue = [[NSOperationQueue alloc] init];
    self.operationQueue.maxConcurrentOperationCount = 1;
    for (NSInteger i = 0; i < assets.count; i++) {
        PHAsset *asset = assets[i];
        // 图片上传operation，上传代码请写到operation内的start方法里，内有注释
        TZImageUploadOperation *operation = [[TZImageUploadOperation alloc] initWithAsset:asset completion:^(UIImage * photo, NSDictionary *info, BOOL isDegraded) {
            if (isDegraded) return;
            NSLog(@"图片获取&上传完成");
        } progressHandler:^(double progress, NSError * _Nonnull error, BOOL * _Nonnull stop, NSDictionary * _Nonnull info) {
            NSLog(@"获取原图进度 %f", progress);
        }];
        [self.operationQueue addOperation:operation];
    }
}
// If allowEditVideo is YES and allowPickingMultipleVideo is NO, When user picking a video, this callback will be called.
// If allowPickingMultipleVideo is YES, video editing is not supported, will call imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:
// 当allowEditVideo是YES且allowPickingMultipleVideo是NO是，如果用户选择了一个视频，下面的代理方法会被执行
// 如果allowPickingMultipleVideo是YES，则不支持编辑视频，将会调用imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingAndEditingVideo:(UIImage *)coverImage outputPath:(NSString *)outputPath error:(NSString *)errorMsg {
    _isAllowEditVideo = YES;
    self->_selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
    self->_selectedAssets = [NSMutableArray arrayWithArray:@[[NSURL fileURLWithPath:outputPath]]];
    
   
    AVAsset *asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:outputPath]];
    NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
    if([tracks count] > 0) {
        AVAssetTrack *videoTrack = [tracks objectAtIndex:0];
        CGAffineTransform t = videoTrack.preferredTransform;//这里的矩阵有旋转角度，转换一下即可
        NSLog(@"=====hello  width:%f===height:%f",videoTrack.naturalSize.width,videoTrack.naturalSize.height);//宽高
        self.width=videoTrack.naturalSize.width;
        self.height=videoTrack.naturalSize.height;
    }
    
    if (outputPath) {
        NSData *data = [NSData dataWithContentsOfFile:outputPath];
        self.videoData=data;
        NSLog(@"视频导出到本地完成,outputPath为:%@",outputPath);
        // Export completed, send video here, send by outputPath or NSData
        // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
//        [self loadputImageTokenwidth:width height:height];
        
        if (coverImage) {
            NSData *data;
            if (UIImagePNGRepresentation(coverImage) == nil) {
                data = UIImageJPEGRepresentation(coverImage, 1.0);
            } else {
                data = UIImagePNGRepresentation(coverImage);
            }
            self.coverData=data;
//            [self loadUpload_token];
        }
    } else {
        NSLog(@"视频导出失败:%@",errorMsg);
    }
    [self.collectionView reloadData];
}

/// 如果用户选择了某张照片下面的代理方法会被执行
/// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
/// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
- (void)imagePickerController:(TZImagePickerController *)picker didSelectAsset:(PHAsset *)asset photo:(UIImage *)photo isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
//    [_selectedAssets addObject:asset];
//    [_selectedPhotos addObject:photo];
//    [self.collectionView reloadData];
}


/// 如果用户取消选择了某张照片下面的代理方法会被执行
/// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
/// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
- (void)imagePickerController:(TZImagePickerController *)picker didDeselectAsset:(PHAsset *)asset photo:(UIImage *)photo isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
//    int index = -1;
//    for (int i = 0; i < _selectedAssets.count; i++) {
//        if ([_selectedAssets[i] isEqual:asset]) {
//            index = i;
//        }
//    }
//    if (index > -1) {
//        [_selectedAssets removeObjectAtIndex:index];
//        [_selectedPhotos removeObjectAtIndex:index];
//        [self.collectionView reloadData];
//    }
}

// Decide album show or not't
// 决定相册显示与否
- (BOOL)isAlbumCanSelect:(NSString *)albumName result:(PHFetchResult *)result {
    /*
    if ([albumName isEqualToString:@"个人收藏"]) {
        return NO;
    }
    if ([albumName isEqualToString:@"视频"]) {
        return NO;
    }*/
    return YES;
}


// Decide asset show or not't
// 决定asset显示与否
- (BOOL)isAssetCanBeDisplayed:(PHAsset *)asset {
    /*
    switch (asset.mediaType) {
        case PHAssetMediaTypeVideo: {
            // 视频时长
            // NSTimeInterval duration = phAsset.duration;
            return NO;
        } break;
        case PHAssetMediaTypeImage: {
            // 图片尺寸
            if (asset.pixelWidth > 3000 || asset.pixelHeight > 3000) {
                 return NO;
            }
            return YES;
        } break;
        case PHAssetMediaTypeAudio:
            return NO;
            break;
        case PHAssetMediaTypeUnknown:
            return NO;
            break;
        default: break;
    }
     */
    return YES;
}

// Decide asset can be selected
// 决定照片能否被选中
- (BOOL)isAssetCanBeSelected:(PHAsset *)asset {
    /*
    switch (asset.mediaType) {
        case PHAssetMediaTypeVideo: {
            // 视频时长
            // NSTimeInterval duration = phAsset.duration;
            return NO;
        } break;
        case PHAssetMediaTypeImage: {
            // 图片尺寸
            if (asset.pixelWidth > 3000 || asset.pixelHeight > 3000) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"不支持选择超大图片" message:nil preferredStyle:UIAlertControllerStyleAlert];
                [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [self.presentedViewController presentViewController:alertController animated:YES completion:nil];
                return NO;
            }
            return YES;
        } break;
        case PHAssetMediaTypeAudio:
            return NO;
            break;
        case PHAssetMediaTypeUnknown:
            return NO;
            break;
        default: break;
    }
     */
    return YES;
}

#pragma mark - Click Event

- (void)deleteBtnClik:(UIButton *)sender {
    if ([self collectionView:self.collectionView numberOfItemsInSection:0] <= _selectedPhotos.count) {
        [_selectedPhotos removeObjectAtIndex:sender.tag];
        [_selectedAssets removeObjectAtIndex:sender.tag];
        [self.collectionView reloadData];
        return;
    }
    
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    [_collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self->_collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self->_collectionView reloadData];
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - Private

/// 打印图片名字
- (void)printAssetsName:(NSArray *)assets {
    NSString *fileName;
    for (PHAsset *asset in assets) {
        fileName = [asset valueForKey:@"filename"];
        // NSLog(@"图片名字:%@",fileName);
    }
}

-(void)loadputImageTokenwidth:(CGFloat)width height:(CGFloat)height{
    //    dispatch_sync(dispatch_get_main_queue(),^{
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
            [SVProgressHUD show ];
            [SVProgressHUD showWithStatus:@"正在加载中，请稍后..."];
    //    });
    
//    NSString *url = [NSString stringWithFormat:@"%@/aliyun_oss_blog_sts/",uploadpurl];
//    [[AFNetManager shareManager] getDataWithURLString:url parameters:nil success:^(NSURLResponse *operation, id successObject) {
//        NSLog(@"%@",successObject);
//        if ([successObject[@"code"] integerValue] == 0) {
//            NSDictionary *dic= successObject[@"data"];
//            NSString *region_id=dic[@"region_id"];
//            NSString *bucket=dic[@"bucket"];
//            NSString *end_point=dic[@"end_point"];
//            NSString *SecurityToken=dic[@"credentials"][@"SecurityToken"];
//            NSString *AccessKeySecret=dic[@"credentials"][@"AccessKeySecret"];
//            NSString *AccessKeyId=dic[@"credentials"][@"AccessKeyId"];
//            NSString *Expiration=dic[@"credentials"][@"Expiration"];
//            [self uploadRegion_id:region_id bucket:bucket end_point:end_point SecurityToken:SecurityToken AccessKeySecret:AccessKeySecret AccessKeyId:AccessKeyId Expiration:Expiration width:width height:height];
//        }else{
//            [SVProgressHUD dismiss];
//            [self showSVProgressHUDStr:successObject[@"message"]];
//        }
//       
//    } failure:^(NSError *error) {
//        [SVProgressHUD dismiss];
//        NSLog(@"%@",error);
//    }];
}
-(void)uploadRegion_id:(NSString *)region_id bucket:(NSString *)bucket end_point:(NSString *)end_point SecurityToken:(NSString *)SecurityToken AccessKeySecret:(NSString *)AccessKeySecret AccessKeyId:(NSString *)AccessKeyId Expiration:(NSString*)Expiration width:(CGFloat)width height:(CGFloat)height{
//    NSString *endpoint = [NSString stringWithFormat:@"https://%@",end_point];
//    id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * _Nullable{
//        OSSFederationToken *token = [OSSFederationToken new];
//        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
//        token.tAccessKey = AccessKeyId;
//        token.tSecretKey = AccessKeySecret;
//        // 从STS服务获取的安全令牌（SecurityToken）。
//        token.tToken = SecurityToken;
//        // 临时访问凭证的过期时间。
//        token.expirationTimeInGMTFormat = Expiration;
//        return token;
//    }];
//
//    self->_client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
//
//    if (self.type==1) {//图片
//
//        [self.imageData removeAllObjects];
//        [self.imagefileNameData removeAllObjects];
//        for (int i=0; i<self->_selectedPhotos.count; i++) {
//
//            //            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            //            // 设置时间格式
//            //            [formatter setDateFormat:@"yyyyMMddHHmmss"];
//            //            NSString *dateString = [formatter stringFromDate:[NSDate date]];
//            //            NSString *fileName = [NSString  stringWithFormat:@"user/photo/%@.jpg", dateString];
//
//            NSString *str=[self randStr];
//            NSMutableString *tmpResult = str.mutableCopy;
//            // 去除“-”
//            NSRange range = [tmpResult rangeOfString:@"-"];
//            while (range.location != NSNotFound) {
//                [tmpResult deleteCharactersInRange:range];
//                range = [tmpResult rangeOfString:@"-"];
//            }
//            NSLog(@"randStr===%@",tmpResult);
//            NSString *dateString =tmpResult;
//            NSString *fileName = [NSString  stringWithFormat:@"blog/blog/%@.jpg", dateString];
//
//            UIImage *image=self->_selectedPhotos[i];
//            NSData *data;
//            if (UIImagePNGRepresentation(image) == nil) {
//                data = UIImageJPEGRepresentation(image, 1.0);
//            } else {
//                data = UIImagePNGRepresentation(image);
//            }
//
//
//            self->_normalUploadRequest = [OSSPutObjectRequest new];
//            self->_normalUploadRequest.bucketName = bucket;
//            //    _normalUploadRequest.objectKey = @"exampledir/src.jpg";
//            self->_normalUploadRequest.objectKey = fileName;
//            //    _normalUploadRequest.uploadingFileURL = [NSURL fileURLWithPath:uploadFilePath];
//            self->_normalUploadRequest.uploadingData=data;
//            self->_normalUploadRequest.isAuthenticationRequired = YES;
//            self->_normalUploadRequest.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//                float progress = 1.f * totalByteSent / totalBytesExpectedToSend;
//                OSSLogDebug(@"上传文件进度: %f", progress);
//            };
//            //    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            OSSTask * task = [self->_client putObject:self->_normalUploadRequest];
//            [task continueWithBlock:^id(OSSTask *task) {
//                //https://huayuoss-public.oss-cn-shenzhen.aliyuncs.com/exampledir/src/20240508152708.jpg
//                //https://huayuoss-user.oss-cn-shenzhen.aliyuncs.com/user/avatar/00005554eb9fcbcb0456c9e90cd55d77.jpeg
//                //https://huayuoss-photo.oss-cn-shenzhen.aliyuncs.com/user/photo/20240605133346.jpg
//
//                if (task.error) {
//                    NSLog(@"上传失败");
//                    [SVProgressHUD dismiss ];
//                    [self showSVProgressHUDStr:@"上传失败"];
//                }else{
//                    NSLog(@"上传成功");
//                    NSString *imageUrl=[NSString stringWithFormat:@"https://%@.%@/%@",bucket,end_point,fileName];
//                    NSLog(@"imageUrl===%@",imageUrl);
//                    [self.imageData addObject:imageUrl];
//                    [self.imagefileNameData addObject:[NSString stringWithFormat:@"/%@",fileName]];
//                    if (self.imageData.count==self->_selectedPhotos.count) {
//                        NSLog(@"%@",self.imageData);
////                        NSString *text = [self.imageData componentsJoinedByString:@","];
//                        NSString *text = [self.imagefileNameData componentsJoinedByString:@","];
//                        NSLog(@"%@",text);
//                        dispatch_async(dispatch_get_main_queue(), ^{
//                            [self loadComplainUserwidth:width height:height videoUrl:@"" imageUrl:self.imageData];
//                        });
//
//                    }
//                }
//                return nil;
//            }];
//            //    });
//        }
//    }else{//视频
//        NSString *str=[self randStr];
//        NSMutableString *tmpResult = str.mutableCopy;
//        // 去除“-”
//        NSRange range = [tmpResult rangeOfString:@"-"];
//        while (range.location != NSNotFound) {
//            [tmpResult deleteCharactersInRange:range];
//            range = [tmpResult rangeOfString:@"-"];
//        }
//        NSLog(@"randStr===%@",tmpResult);
//        NSString *dateString =tmpResult;
//        NSString *fileName = [NSString  stringWithFormat:@"blog/blog/%@.mp4", dateString];
//
//
//        self->_normalUploadRequest = [OSSPutObjectRequest new];
//        self->_normalUploadRequest.bucketName = bucket;
//        //    _normalUploadRequest.objectKey = @"exampledir/src.jpg";
//        self->_normalUploadRequest.objectKey = fileName;
//        //    _normalUploadRequest.uploadingFileURL = [NSURL fileURLWithPath:uploadFilePath];
//        self->_normalUploadRequest.uploadingData=self.videoData;
//        self->_normalUploadRequest.isAuthenticationRequired = YES;
//        self->_normalUploadRequest.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//            float progress = 1.f * totalByteSent / totalBytesExpectedToSend;
//            OSSLogDebug(@"上传文件进度: %f", progress);
//        };
//        //    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        OSSTask * task = [self->_client putObject:self->_normalUploadRequest];
//        [task continueWithBlock:^id(OSSTask *task) {
//            //https://huayuoss-public.oss-cn-shenzhen.aliyuncs.com/exampledir/src/20240508152708.jpg
//            //https://huayuoss-user.oss-cn-shenzhen.aliyuncs.com/user/avatar/00005554eb9fcbcb0456c9e90cd55d77.jpeg
//            //https://huayuoss-photo.oss-cn-shenzhen.aliyuncs.com/user/photo/20240605133346.jpg
//
//
//            if (task.error) {
//                NSLog(@"上传失败");
//                [SVProgressHUD dismiss ];
//                [self showSVProgressHUDStr:@"上传失败"];
//            }else{
//                NSLog(@"上传成功");
//                NSString *imageUrl=[NSString stringWithFormat:@"https://%@.%@/%@",bucket,end_point,fileName];
//                NSLog(@"imageUrl===%@",imageUrl);
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self loadComplainUserwidth:width height:height videoUrl:imageUrl imageUrl:nil];
//                });
//            }
//            return nil;
//        }];
//    }
}
-(void)loadComplainUserwidth:(CGFloat)width height:(CGFloat)height videoUrl:(NSString *)videoUrl imageUrl:(NSArray *)imageUrl{
    NSString *type=@"1";//视频1
    if (self.type==1) {//图片3
        type=@"3";
    }

    
//    NSString *str=[self toJsonStrWithArray:self.imageData];
//    NSString *url = [NSString stringWithFormat:@"%@/add",blogpurl];
//    NSDictionary *param = @{};
//    if (self.type==1) {//图片
//        param = @{
//                @"type":type,
//                @"content":self.textView.text,
//                @"media":str,
//                };
//    }else{//视频
////        videoUrl=[NSString stringWithFormat:@"/%@",videoUrl];
//        NSArray *a=[NSArray arrayWithObject:videoUrl];
//        str=[self toJsonStrWithArray:a];
//        NSString *w=[NSString stringWithFormat:@"%f",self.width];
//        NSString *h=[NSString stringWithFormat:@"%f",self.height];
//        NSArray *video_size=@[w,h];
//        param = @{
//                @"type":type,
//                @"content":self.textView.text,
//                @"media":str,
//                @"video_size":video_size
//                };
//    }
    
//    [[AFNetManager shareManager] postDataWithURLString:url parameters:param success:^(NSURLResponse *operation, id successObject) {
//        NSLog(@"%@",successObject);
//        [SVProgressHUD dismiss];
//        if ([successObject[@"code"] integerValue] == 0) {
//            [self showSVProgressHUDStr:@"动态发布成功，等待审核"];
//            [self dismissViewControllerAnimated:YES completion:^{
//                
//            }];
//           
//        } else {
//            [self showSVProgressHUDStr:successObject[@"message"]];
//        }
//        
//    } failure:^(NSError *error) {
//        [SVProgressHUD dismiss];
//        NSLog(@"%@",error);
//    }];
}

-(void)loadUpload_token{
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD show ];
    [SVProgressHUD showWithStatus:@"正在加载中，请稍后..."];
    
    NSDictionary *param =@{
//                            @"type":@(2)
                            @"type":@(3)
                          };
    NSString *path=@"/system/upload_token";
    NSString *url1 = [NSString stringWithFormat:@"%@%@",baseUrl,path];
//    [[AFNetManager shareManager] postDataWithURLString:url1 path:path parameters:param success:^(NSURLResponse *operation, id successObject) {
//        
//        NSString *result=successObject[@"result"];
//        NSDictionary *dic=@{};
//        if ([successObject[@"result"] isKindOfClass:[NSString class]]) {
//            //解密Base64编码的字符串
//            NSString *decryptedString = [AES128 decryptString:result key:dataKey iv:dataIv];
//            dic=[AES128 dictionaryWithJsonString:decryptedString];
//            NSLog(@"json解析===%@",dic);
//        }
//        
//        if ([successObject[@"code"] integerValue] == 200) {
//            
//            NSString *expiredTime=[NSString stringWithFormat:@"%@",dic[@"expiredTime"]];//过期时间戳
//            NSString *expiration=[NSString stringWithFormat:@"%@",dic[@"expiration"]];//过期时间字符串
//            NSString *requestId=[NSString stringWithFormat:@"%@",dic[@"requestId"]];//请求ID
//            NSString *startTime=[NSString stringWithFormat:@"%@",dic[@"startTime"]];//开始时间戳
//            NSDictionary *credentials=dic[@"credentials"];//上传凭证信息
//            NSString *prefix=[NSString stringWithFormat:@"%@",dic[@"prefix"]];//上传凭证信息
//            
//            NSString *sessionToken=[NSString stringWithFormat:@"%@",credentials[@"sessionToken"]];//会话令牌
//            NSString *tmpSecretId=[NSString stringWithFormat:@"%@",credentials[@"tmpSecretId"]];//临时密钥ID
//            NSString *tmpSecretKey=[NSString stringWithFormat:@"%@",credentials[@"tmpSecretKey"]];//临时密钥Key
//            
//            [self uploadExpiredTime:expiredTime expiration:expiration requestId:requestId startTime:startTime prefix:prefix sessionToken:sessionToken tmpSecretId:tmpSecretId tmpSecretKey:tmpSecretKey uploadFilePath:self->uploadFilePath imageData:nil imageOrAudio:@"" audioData:nil duration:@"0"];
//        } else {
//            [SVProgressHUD dismiss];
//            [self showSVProgressHUDStr:successObject[@"message"]];
//        }
//
//    } failure:^(NSError *error) {
//        [SVProgressHUD dismiss];
//        NSLog(@"错误：%@",error);
//    }];
}


-(void)uploadExpiredTime:(NSString *)expiredTime expiration:(NSString *)expiration requestId:(NSString *)requestId  startTime:(NSString *)startTime  prefix:(NSString *)prefix  sessionToken:(NSString *)sessionToken  tmpSecretId:(NSString *)tmpSecretId  tmpSecretKey:(NSString *)tmpSecretKey uploadFilePath:(NSString *)uploadFilePath imageData:(NSData *)imageData imageOrAudio:(NSString *)imageOrAudio audioData:(NSData *)audioData duration:(NSString *)duration{
    
    if (self.type==1) {//图片
        
        [self.imageData removeAllObjects];
        [self.imagefileNameData removeAllObjects];
        
        for (int i=0; i<self->_selectedPhotos.count; i++) {
            
            int randomNumber = arc4random_uniform(900) + 100;
            NSString *timeStamp=[AES128 getNowTimeStamp];
            NSString *houzhuo=@".jpg";
            NSString *object=[NSString stringWithFormat:@"%@%@%d%@",prefix,timeStamp,randomNumber,houzhuo];
            NSDictionary *saveOpen_app_config1 = [Config getOpenAppConfig];
            NSString *cos_bucket_name=@"";
            NSString *cos_region=@"";
            NSString *cos_url=@"";
            
            if (saveOpen_app_config1!=nil) {
                cos_bucket_name=saveOpen_app_config1[@"cos_bucket_name"];
                NSLog(@"cos_bucket_name=%@",cos_bucket_name);
                cos_region=saveOpen_app_config1[@"cos_region"];
                NSLog(@"cos_region=%@",cos_region);
                cos_url=saveOpen_app_config1[@"cos_url"];
                NSLog(@"cos_url=%@",cos_url);
            }
            
            //    QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
            /** 本地文件路径，请确保 URL 是以 file:// 开头，格式如下 ：
             1. [NSURL URLWithString:@"file:////var/mobile/Containers/Data/Application/DBPF7490-D5U8-4ABF-A0AF-CC49D6A60AEB/Documents/exampleobject"]
             2. [NSURL fileURLWithPath:@"/var/mobile/Containers/Data/Application/DBPF7490-D5U8-4ABF-A0AF-CC49D6A60AEB/Documents/exampleobject"]
             */
            //    NSURL* url = [NSURL fileURLWithPath:uploadFilePath];
            
            
            NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:[startTime integerValue]];
            NSDate *expirationDate = [NSDate dateWithTimeIntervalSince1970:[expiredTime integerValue]];
            
            QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
            QCloudCredential * credential = [QCloudCredential new];
            credential.secretID = tmpSecretId;
            credential.secretKey = tmpSecretKey;
            credential.token = sessionToken;
            credential.startDate = startDate;
            credential.expirationDate = expirationDate;
            UIImage *image=self->_selectedPhotos[i];
            NSData *data;
            if (UIImagePNGRepresentation(image) == nil) {
                data = UIImageJPEGRepresentation(image, 1.0);
            } else {
                data = UIImagePNGRepresentation(image);
            }
            
            // 设置临时密钥
            put.credential = credential;
            // 本地文件路径
            //    NSURL* url = [NSURL fileURLWithPath:uploadFilePath];
            //    NSURL* url =[NSURL URLWithString:uploadFilePath];
            // 存储桶名称，由 BucketName-Appid 组成，可以在 COS 控制台查看 https://console.cloud.tencent.com/cos5/bucket
            put.bucket = cos_bucket_name;
            // 对象键，是对象在 COS 上的完整路径，如果带目录的话，格式为 "video/xxx/movie.mp4"
            put.object = object;
            //需要上传的对象内容。可以传入 NSData* 或者 NSURL* 类型的变量
            //    put.body =  url;
            put.body=data;
            //监听上传进度
            [put setSendProcessBlock:^(int64_t bytesSent,
                                       int64_t totalBytesSent,
                                       int64_t totalBytesExpectedToSend) {
                //      bytesSent                 本次要发送的字节数（一个大文件可能要分多次发送）
                //      totalBytesSent            已发送的字节数
                //      totalBytesExpectedToSend  本次上传要发送的总字节数（即一个文件大小）
                float progress = 1.f * totalBytesSent / totalBytesExpectedToSend;
                NSLog(@"上传文件进度: %f", progress);
            }];
            //https://cos.nnyc123.cn/dev/chat/4/1004/1744765911239.jpg
            
            //监听上传结果
            [put setFinishBlock:^(id outputObject, NSError *error) {
                
                //可以从 outputObject 中获取 response 中 etag 或者自定义头部等信息
                NSDictionary * result = (NSDictionary *)outputObject;
                NSLog(@"%@",result);
                if (error==nil) {
                    NSString *url=[NSString stringWithFormat:@"%@%@",cos_url,object];
                    NSLog(@"%@",url);
                    [self.imageData addObject:url];
//                    [self.imagefileNameData addObject:[NSString stringWithFormat:@"/%@",fileName]];
                    if (self.imageData.count==self->_selectedPhotos.count) {
                        NSLog(@"%@",self.imageData);
//                        NSString *text = [self.imageData componentsJoinedByString:@","];
                        NSString *text = [self.imagefileNameData componentsJoinedByString:@","];
                        NSLog(@"%@",text);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self dynamic_release:@"" imageData:self.imageData];
                        });
                    }
                    
                }else{
                    [SVProgressHUD dismiss];
                    [self showSVProgressHUDStr:@"上传失败"];
                }
                
            }];
            
            [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
        }
        
    }else{
        
        
        int randomNumber = arc4random_uniform(900) + 100;
        NSString *timeStamp=[AES128 getNowTimeStamp];
        NSString *houzhuo=@".jpg";
        NSString *object=[NSString stringWithFormat:@"%@%@%d%@",prefix,timeStamp,randomNumber,houzhuo];
        NSDictionary *saveOpen_app_config1 = [Config getOpenAppConfig];
        NSString *cos_bucket_name=@"";
        NSString *cos_region=@"";
        NSString *cos_url=@"";
        
        if (saveOpen_app_config1!=nil) {
            cos_bucket_name=saveOpen_app_config1[@"cos_bucket_name"];
            NSLog(@"cos_bucket_name=%@",cos_bucket_name);
            cos_region=saveOpen_app_config1[@"cos_region"];
            NSLog(@"cos_region=%@",cos_region);
            cos_url=saveOpen_app_config1[@"cos_url"];
            NSLog(@"cos_url=%@",cos_url);
        }
        
        //    QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
        /** 本地文件路径，请确保 URL 是以 file:// 开头，格式如下 ：
         1. [NSURL URLWithString:@"file:////var/mobile/Containers/Data/Application/DBPF7490-D5U8-4ABF-A0AF-CC49D6A60AEB/Documents/exampleobject"]
         2. [NSURL fileURLWithPath:@"/var/mobile/Containers/Data/Application/DBPF7490-D5U8-4ABF-A0AF-CC49D6A60AEB/Documents/exampleobject"]
         */
        //    NSURL* url = [NSURL fileURLWithPath:uploadFilePath];
        
        
        NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:[startTime integerValue]];
        NSDate *expirationDate = [NSDate dateWithTimeIntervalSince1970:[expiredTime integerValue]];
        
        QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
        QCloudCredential * credential = [QCloudCredential new];
        credential.secretID = tmpSecretId;
        credential.secretKey = tmpSecretKey;
        credential.token = sessionToken;
        credential.startDate = startDate;
        credential.expirationDate = expirationDate;
      
        // 设置临时密钥
        put.credential = credential;
        // 本地文件路径
        //    NSURL* url = [NSURL fileURLWithPath:uploadFilePath];
        //    NSURL* url =[NSURL URLWithString:uploadFilePath];
        // 存储桶名称，由 BucketName-Appid 组成，可以在 COS 控制台查看 https://console.cloud.tencent.com/cos5/bucket
        put.bucket = cos_bucket_name;
        // 对象键，是对象在 COS 上的完整路径，如果带目录的话，格式为 "video/xxx/movie.mp4"
        put.object = object;
        //需要上传的对象内容。可以传入 NSData* 或者 NSURL* 类型的变量
        //    put.body =  url;
        put.body=self.coverData;
        //监听上传进度
        [put setSendProcessBlock:^(int64_t bytesSent,
                                   int64_t totalBytesSent,
                                   int64_t totalBytesExpectedToSend) {
            //      bytesSent                 本次要发送的字节数（一个大文件可能要分多次发送）
            //      totalBytesSent            已发送的字节数
            //      totalBytesExpectedToSend  本次上传要发送的总字节数（即一个文件大小）
            float progress = 1.f * totalBytesSent / totalBytesExpectedToSend;
            NSLog(@"上传文件进度: %f", progress);
        }];
        //https://cos.nnyc123.cn/dev/chat/4/1004/1744765911239.jpg
        
        //监听上传结果
        [put setFinishBlock:^(id outputObject, NSError *error) {
            
            //可以从 outputObject 中获取 response 中 etag 或者自定义头部等信息
            NSDictionary * result = (NSDictionary *)outputObject;
            NSLog(@"%@",result);
            if (error==nil) {
                NSString *url=[NSString stringWithFormat:@"%@%@",cos_url,object];
                NSLog(@"%@",url);
               
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self dynamic_release:url imageData:nil];
//                });
                
                self.coverUrl=url;
                
                [self videouploadExpiredTime:expiredTime expiration:expiration requestId:requestId startTime:startTime prefix:prefix sessionToken:sessionToken tmpSecretId:tmpSecretId tmpSecretKey:tmpSecretKey];
               
            }else{
                [SVProgressHUD dismiss];
                [self showSVProgressHUDStr:@"上传失败"];
            }
            
        }];
        
        [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
    }
}
-(void)videouploadExpiredTime:(NSString *)expiredTime expiration:(NSString *)expiration requestId:(NSString *)requestId  startTime:(NSString *)startTime  prefix:(NSString *)prefix  sessionToken:(NSString *)sessionToken  tmpSecretId:(NSString *)tmpSecretId  tmpSecretKey:(NSString *)tmpSecretKey{
    
    
    int randomNumber = arc4random_uniform(900) + 100;
    NSString *timeStamp=[AES128 getNowTimeStamp];
    NSString *houzhuo=@".mp4";
    NSString *object=[NSString stringWithFormat:@"%@%@%d%@",prefix,timeStamp,randomNumber,houzhuo];
    NSDictionary *saveOpen_app_config1 = [Config getOpenAppConfig];
    
    NSString *cos_bucket_name=@"";
    NSString *cos_region=@"";
    NSString *cos_url=@"";
    
    if (saveOpen_app_config1!=nil) {
        cos_bucket_name=saveOpen_app_config1[@"cos_bucket_name"];
        cos_region=saveOpen_app_config1[@"cos_region"];
        cos_url=saveOpen_app_config1[@"cos_url"];
    }
    
    QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];
    //        configuration.appID = @"1250000000";
    QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];
    endpoint.regionName = cos_region;
    // 使用 HTTPS
    endpoint.useHTTPS = true;
    configuration.endpoint = endpoint;
    // 初始化 COS 服务示例
    [QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];
    [QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:
     configuration];
    
    NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:[startTime integerValue]];
    NSDate *expirationDate = [NSDate dateWithTimeIntervalSince1970:[expiredTime integerValue]];
    
    QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
    QCloudCredential * credential = [QCloudCredential new];
    credential.secretID = tmpSecretId;
    credential.secretKey = tmpSecretKey;
    credential.token = sessionToken;
    credential.startDate = startDate;
    credential.expirationDate = expirationDate;
    put.credential = credential;
    put.bucket = cos_bucket_name;
    put.object = object;
    put.body=self.videoData;
    //监听上传进度
    [put setSendProcessBlock:^(int64_t bytesSent,
                               int64_t totalBytesSent,
                               int64_t totalBytesExpectedToSend) {
        //      bytesSent                 本次要发送的字节数（一个大文件可能要分多次发送）
        //      totalBytesSent            已发送的字节数
        //      totalBytesExpectedToSend  本次上传要发送的总字节数（即一个文件大小）
        float progress = 1.f * totalBytesSent / totalBytesExpectedToSend;
        NSLog(@"上传文件进度: %f", progress);
    }];
    
    //监听上传结果
    [put setFinishBlock:^(id outputObject, NSError *error) {
        
        //可以从 outputObject 中获取 response 中 etag 或者自定义头部等信息
        NSDictionary * result = (NSDictionary *)outputObject;
        NSLog(@"%@",result);
        if (error==nil) {
            NSString *url=[NSString stringWithFormat:@"%@%@",cos_url,object];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                
                self.videoUrl=url;
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [self dynamic_release:url imageData:nil];
                                });
            });
            
        }else{
            [SVProgressHUD dismiss];
           
            [self showSVProgressHUDStr:@"上传失败"];
        }
        
    }];
    [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
}
-(void)dynamic_release:(NSString *)videourl imageData:(NSArray *)imageData{
    
    NSDictionary *param = @{};
    if (self.type==1) {//图片
        param = @{
                @"content":self.textView.text,
                @"resource":imageData,
                @"type":@(1),
                @"location":@""
                };
    }else{//视频
        param = @{
                @"content":self.textView.text,
                @"resource":@[self.videoUrl,self.coverUrl,@(1)],
                @"type":@(2),
                @"location":@""
                };
    }
    
    NSString *path=@"/dynamic/release";
    NSString *url1 = [NSString stringWithFormat:@"%@%@",baseUrl,path];
//    [[AFNetManager shareManager] postDataWithURLString:url1 path:path parameters:param success:^(NSURLResponse *operation, id successObject) {
//        [SVProgressHUD dismiss];
//        NSString *result=successObject[@"result"];
//        NSDictionary *dic=@{};
//        if ([successObject[@"result"] isKindOfClass:[NSString class]]) {
//            //解密Base64编码的字符串
//            NSString *decryptedString = [AES128 decryptString:result key:dataKey iv:dataIv];
//            dic=[AES128 dictionaryWithJsonString:decryptedString];
//            NSLog(@"json解析===%@",dic);
//        }
//        
//        if ([successObject[@"code"] integerValue] == 200) {
//            [self showSVProgressHUDStr:@"动态发布成功，等待审核"];
//            [self dismissViewControllerAnimated:YES completion:^{
//                
//            }];
//            
//        } else {
//            [self showSVProgressHUDStr:successObject[@"message"]];
//        }
//        
//    } failure:^(NSError *error) {
//        [SVProgressHUD dismiss];
//        NSLog(@"错误：%@",error);
//    }];
}
- (NSString *)toJsonStrWithArray:(NSArray *)arr {
    if ([arr isKindOfClass:[NSString class]]) {
        return (NSString *)arr;
    }
    NSError *parseError = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    jsonStr = [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    if (parseError) {
        jsonStr = @"";
    }
    return jsonStr;
}

- (NSString *)randStr {
    CFUUIDRef uuidObj = CFUUIDCreate(nil);
    CFStringRef uuidString = CFUUIDCreateString(nil, uuidObj);
    NSString *result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(uuidObj);
    CFRelease(uuidString);
    return result;
}


@end
